package com.mdnote.structure.hashtable;

import com.sun.org.apache.bcel.internal.generic.BREAKPOINT;

import javax.jws.soap.SOAPBinding;
import java.io.Serializable;
import java.util.Scanner;

/**
 * @author Rhythm-2019
 * @version 1.0
 * @date 2020/8/28
 * @description 哈希表
 */
public class UserHashTable {

    // 链表数组
    private UserBucketLinkedList[] userBucketLinkedLists;

    private int size;

    public UserHashTable(int size) {
        this.userBucketLinkedLists = new UserBucketLinkedList[size];
        this.size = size;
        for (int i = 0; i < size; i++) {
            this.userBucketLinkedLists[i] = new UserBucketLinkedList(i);
        }
    }

    public void add(User user) {
        int index = hash(user.getId());
        this.userBucketLinkedLists[index].addByOrder(user);
    }

    public void remove(Serializable id) {
        int index = hash(id);
        this.userBucketLinkedLists[index].remove(id);
    }

    public void list() {
        for (int i = 0; i < this.userBucketLinkedLists.length; i++) {
            this.userBucketLinkedLists[i].list();
        }
    }

    private int hash(Serializable id) {
        return Math.toIntExact((Long) id % size);
    }

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        UserHashTable userHashTable = new UserHashTable(4);
        OUTER:
        while (true) {
            System.out.println("[A] add");
            System.out.println("[R] remove");
            System.out.println("[L] list");
            System.out.println("[E] exit");
            char operationChar = scanner.next().charAt(0);

            switch (operationChar) {
                case 'A':
                    User user = new User();
                    System.out.print("id:");
                    user.setId(scanner.nextLong());
                    System.out.print("usAername：");
                    user.setUsername(scanner.next());
                    System.out.println();
                    userHashTable.add(user);
                    break;
                case 'r':
                    System.out.print("id");
                    ;userHashTable.remove(scanner.nextLong());
                    break;
                case 'L':
                    userHashTable.list();
                    break;
                case 'E':
                    break OUTER;
                default:
                    System.out.println("非法操作");
            }
        }
    }

}
